package d.qapaper.main;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import d.qapaper.R;
import d.qapaper.bean.CategoriesInfo;
import d.qapaper.bean.Project;
import d.qapaper.bean.Question;
import d.qapaper.bean.TemplateInfo;
import d.qapaper.bean.Unit;
import d.qapaper.bean.User;
import d.qapaper.common.Constants;
import d.qapaper.service.ConfigReadService;
import d.qapaper.service.SaxReadService;
import d.qapaper.tool.Base64Util;
import d.qapaper.tool.ImageUtil;
import d.qapaper.tool.MD5;

/**
 * @author Kaven 2011-5-30
 */
public class Qapaper extends Activity {
	// 信息反饋
	private int info;
	private HashMap<String,Integer> msgMap=new HashMap<String, Integer>();
	String appPath;
	String fileDirFile;
	// 程序目錄 /mnt/sdcard/appPath
	String appFilePath;
	// 输出文件路径
	String outPath;
	// 输入文件路径
	String inputPath;
	// 程序 讀取模版 目錄 /mnt/sdcard/appPath/template
	String templateFilePath;
	// 程序 讀取問卷目錄
	String questionPath;
	// 程序 讀取問題分類目錄
	String qusTypePath;
	// 頭尾圖片目錄
	String imagePath;
	// 用户路径
	String userPath;
	// 项目文件
	String projectPath;
	// 单位文件
	String unitPath;
	// 用户对象
	private User user;
	Dialog dialog = null;
	AlertDialog.Builder logindialog = null;
	AlertDialog templateDialog = null;
	// 问题库XML的文件名
	private String questionFileName;
	// 问卷的编号
	private int pID = 100001;
	private SharedPreferences pidShared;
	// 頭部view
	private View headView;
	// 標題字體大小
	private int titleSize = 20;
	// 子標題字體大小
	private int subTitleSize = 20;
	// 分類字體大小
	private int cnameSize = 26;
	// 配置map
	private HashMap<String, String> configMap = null;
	private String global_title;
	private String global_subtitle;
	private String tempSpinnerIndex = "0";
	private String tid;
	private TreeMap<String, TemplateInfo> templateMap = new TreeMap<String, TemplateInfo>();
	Base64Util base64Util=new Base64Util();
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		wifi.setWifiEnabled(false);
		fillMsgMap();
		// 判斷是否加載sd卡
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			appPath = getResources().getString(R.string.appPath);
			fileDirFile = Environment.getExternalStorageDirectory()
					.getAbsolutePath();
			appFilePath = fileDirFile.toString() + File.separatorChar + appPath;
			inputPath = appFilePath + File.separatorChar + "input";

			outPath = appFilePath + File.separatorChar + "output";
			createConfigFile();
			configMap = getConfigMap();
			if (null != configMap.get("isUserPath")) {
				if ("1".equalsIgnoreCase(configMap.get("isUserPath"))) {
					if (null != configMap.get("userPath")) {
						fileDirFile = configMap.get("userPath");
						appFilePath = fileDirFile.toString()
								+ File.separatorChar + appPath;
						inputPath = appFilePath + File.separatorChar + "input";

						outPath = appFilePath + File.separatorChar + "output";
						Log.i("info", "--------使用自定義路徑");
					}
				}
			}
			appFilePath = fileDirFile.toString() + File.separatorChar + appPath;
			inputPath = appFilePath + File.separatorChar + "input";

			outPath = appFilePath + File.separatorChar + "output";
			mkDir();
			if (checkFile()) {
				createLogin();

			} else {
				dialog = new AlertDialog.Builder(this)
						.setTitle("提示")
						.setMessage(returnMsgSel("nofile"))
						.setPositiveButton("確定",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										dialog.dismiss();
										Qapaper.this.finish();
									}
								}).create();
				dialog.show();
			}

			pidShared = this.getSharedPreferences("pid", Activity.MODE_PRIVATE);
		} else {
			info = returnMsgSel("withOutSD");
			Toast.makeText(Qapaper.this, info, 5).show();
			this.finish();
		}
		setContentView(R.layout.main);
	}

	/**
	 * 生成問卷介面
	 */
	private LinearLayout createPaper(String isShowInput) {
		// 尾部圖片
		ImageView imageView = new ImageView(Qapaper.this);
		imageView.setTag("foot");
		LinearLayout linearLayout = new LinearLayout(Qapaper.this);
		linearLayout.setOrientation(LinearLayout.VERTICAL);
		LinearLayout questionLayout = new LinearLayout(Qapaper.this);
		questionLayout.setTag("question_container");
		questionLayout.setOrientation(LinearLayout.VERTICAL);
		try {

			createViewItem createViewItem = new createViewItem(Qapaper.this,
					isShowInput);
			SaxReadService readService = new SaxReadService();
			InputStream inputStream;
			// 讀取頭尾部圖片
			File imageHead = new File(inputPath + "/head.png");
			File imageFoot = new File(inputPath + "/foot.png");
			if (imageHead.exists()) {
				createViewItem.createBindImage(imageHead, 1);
			}
			if (imageFoot.exists()) {
				imageView.setImageBitmap(ImageUtil.getRoundedCornerBitmap(
						imageFoot.getPath().toString(), 6, 2));
			}
			// 讀取模版
			TableLayout titleLayout = new TableLayout(Qapaper.this);
			TextView title = new TextView(this);
			title.setTextSize(titleSize);
			title.setTag("head_title");
			title.setTextColor(Color.BLACK);
			title.setText(global_title);
			title.setGravity(Gravity.CENTER);
			TextView subTitle = new TextView(this);
			subTitle.setTextSize(subTitleSize);
			subTitle.setTextColor(Color.BLACK);
			subTitle.setText(global_subtitle);
			subTitle.setTag("head_subtitle");
			inputStream = new FileInputStream(projectPath);
			List<Project> peojectList = readService.getProjectInfo(inputStream,
					5);
			inputStream = new FileInputStream(unitPath);
			List<Unit> unitList = readService.getUnitInfo(inputStream, 6);
			headView = createViewItem.createProjectInfo(peojectList, configMap);

			// 添加spinner模板选择
			int tempLen = templateMap.keySet().size();
			if (tempLen > 1) {
				Spinner templateSpin = new Spinner(Qapaper.this);
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
						android.R.layout.simple_spinner_item);
				Set<String> keys = templateMap.keySet();

				for (String f : keys) {
						adapter.add(templateMap.get(f).getName());
				}
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				templateSpin.setAdapter(adapter);
				titleLayout.addView(templateSpin, new LayoutParams(
						LayoutParams.FILL_PARENT,
						android.view.WindowManager.LayoutParams.WRAP_CONTENT));
				templateSpin
						.setOnItemSelectedListener(new OnItemSelectedListener() {

							@Override
							public void onItemSelected(AdapterView<?> arg0,
									View arg1, int arg2, long arg3) {
								ScrollView scrollView = (ScrollView) Qapaper.this
										.findViewById(R.id.content_body);
								TextView tv = (TextView) arg1;
								tv.setTextSize(Integer.parseInt(configMap
										.get("unit")));
								;
								TextView title = (TextView) scrollView
										.findViewWithTag("head_title");
								title.setText(templateMap.get(
										String.valueOf(arg2)).getTitle());
								TextView subtitle = (TextView) scrollView
										.findViewWithTag("head_subtitle");
								subtitle.setText(templateMap.get(
										String.valueOf(arg2)).getSubtitle());
								tid = templateMap.get(String.valueOf(arg2))
										.getTid();
								File file = new File(questionPath);
								// 做问卷选择
								LinearLayout linearLayout = (LinearLayout) scrollView
										.findViewWithTag("question_container");
								linearLayout.removeAllViews();
								createQuestionArea(linearLayout, file,
										templateMap.get(String.valueOf(arg2))
												.getFeedback());
							}

							@Override
							public void onNothingSelected(AdapterView<?> arg0) {
								// TODO Auto-generated method stub

							}

						});
				templateSpin.setSelection(Integer.parseInt(tempSpinnerIndex));

			}

			titleLayout.addView(title, new LayoutParams(
					LayoutParams.FILL_PARENT,
					android.view.WindowManager.LayoutParams.WRAP_CONTENT));
			titleLayout.addView(headView, new LayoutParams(
					LayoutParams.FILL_PARENT,
					android.view.WindowManager.LayoutParams.WRAP_CONTENT));
			titleLayout.addView(createViewItem.createHeadUnit(unitList,
					configMap), new LayoutParams(LayoutParams.FILL_PARENT,
					android.view.WindowManager.LayoutParams.WRAP_CONTENT));
			titleLayout.addView(subTitle, new LayoutParams(
					LayoutParams.FILL_PARENT,
					android.view.WindowManager.LayoutParams.WRAP_CONTENT));
			linearLayout.addView(titleLayout, new LayoutParams(
					LayoutParams.FILL_PARENT,
					android.view.WindowManager.LayoutParams.WRAP_CONTENT));
			File file = new File(questionPath);

			// 做问卷选择
			createQuestionArea(questionLayout, file, isShowInput);

		} catch (Exception e) {
			e.printStackTrace();
		}
		// 確定按鈕
		Button submitBtn = new Button(Qapaper.this);
		submitBtn.setText("提交");
		submitBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				getQuestionsValue();
			}
		});
		// 重置按钮
		Button resetBtn = new Button(Qapaper.this);
		resetBtn.setText("重置");
		resetBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				reset();
			}
		});

		linearLayout.addView(questionLayout, new LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		LinearLayout submitAreaLayout = new LinearLayout(Qapaper.this);
		submitAreaLayout.setLayoutParams(new LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		submitAreaLayout.setGravity(Gravity.CENTER_HORIZONTAL);
		submitAreaLayout.setOrientation(LinearLayout.HORIZONTAL);
		submitAreaLayout.addView(submitBtn, new LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		submitAreaLayout.addView(resetBtn, new LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		linearLayout.addView(submitAreaLayout, new LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		linearLayout.addView(imageView, new LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		return linearLayout;
	}

	/**
	 * 創建app目录
	 * 
	 * @return
	 */
	private void mkDir() {
		File file = new File(appFilePath);
		// 不存在則創建
		if (!file.exists()) {
			// 創建程序目錄
			file.mkdir();
		}

		// 創建输入目錄
		file = new File(inputPath);
		if (!file.exists()) {
			file.mkdir();
		}

		// 創建输出目錄
		file = new File(outPath);
		if (!file.exists()) {
			file.mkdir();
		}
		questionPath = inputPath + File.separatorChar + "question";
		// 創建問題目錄
		file = new File(questionPath);
		if (!file.exists()) {
			file.mkdir();
		}

	}

	private boolean checkFile() {
		boolean flag = true;
		templateFilePath = inputPath + File.separatorChar + "template_info.xml";
		qusTypePath = inputPath + File.separatorChar + "categories_info.xml";
		userPath = inputPath + File.separatorChar + "user.xml";
		projectPath = inputPath + File.separatorChar + "project_info.xml";
		unitPath = inputPath + File.separatorChar + "unit_info.xml";
		File file = new File(templateFilePath);
		if (!file.exists()) {
			info = returnMsgSel("noTemplate");
			Toast.makeText(Qapaper.this, info, 5).show();
			flag = false;
		}
		file = new File(qusTypePath);
		if (!file.exists()) {
			info = returnMsgSel("noType");
			Toast.makeText(Qapaper.this, info, 5).show();
			flag = false;
		}
		file = new File(userPath);
		if (!file.exists()) {
			info = returnMsgSel("noUserPath");
			Toast.makeText(Qapaper.this, info, 5).show();
			flag = false;
		}
		file = new File(projectPath);
		if (!file.exists()) {
			info = returnMsgSel("noProjectPath");
			Toast.makeText(Qapaper.this, info, 5).show();
			flag = false;
		}
		file = new File(unitPath);
		if (!file.exists()) {
			info = returnMsgSel("noUnitPath");
			Toast.makeText(Qapaper.this, info, 5).show();
			flag = false;
		}
		return flag;
	}

	/**
	 * 創建登錄
	 */
	private void createLogin() {
		logindialog = new AlertDialog.Builder(Qapaper.this);
		LayoutInflater factory = LayoutInflater.from(Qapaper.this);
		final View view = factory.inflate(R.layout.login, null);
		logindialog.setView(view);
		logindialog.setTitle("登錄")
				.setPositiveButton("登錄", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						try {
							Qapaper.this.isUser(userPath, view);
						} catch (Exception e) {
							e.printStackTrace();
							Log.e("error", e.toString());
						}

					}
				})
				.setNegativeButton("退出", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Dialog exitDialog = new AlertDialog.Builder(
								Qapaper.this)
								.setTitle("提示")
								.setMessage(returnMsgSel("exitWarn"))
								.setPositiveButton("是",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												dialog.dismiss();
												System.exit(0);
											}
										})
								.setNegativeButton("否",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												dialog.dismiss();
											}
										}).create();
						exitDialog.show();
						// dialog.dismiss();
						// Qapaper.this.finish();

					}
				}).show();
	}

	/**
	 * 获取问卷答题选项
	 */
	public void getQuestionsValue() {
		try {
			RadioButton radioButton = null;
			ScrollView scrollView = (ScrollView) this
					.findViewById(R.id.content_body);
			// 答卷題目區域
			boolean isUnFilled = false;
			final StringBuilder pAns = new StringBuilder("");
			final StringBuilder pReason = new StringBuilder("");
			LinearLayout answerArea = null;
			LinearLayout templLayout = null;
			View view = null;
			EditText reasText = null;
			String temp="";
			for (Map<Integer, Integer> questionMap : Constants.questionViewsList) {
				Object[] keyArray = questionMap.keySet().toArray();
				for (Object key : keyArray) {

					switch (questionMap.get(key)) {
					// RadioButton
					case 1:
						answerArea = (LinearLayout) this.findViewById(Integer
								.parseInt(key.toString()));
						
						for (int i = 0; i < answerArea.getChildCount(); i++) {
							view = answerArea.getChildAt(i);
							if (view instanceof LinearLayout) {
								templLayout = (LinearLayout) view;
								Log.i("info",
										"--------------"
												+ templLayout.getChildCount());
								for (int y = 0; y < templLayout.getChildCount(); y++) {
									radioButton = (RadioButton) templLayout
											.getChildAt(y);
									Log.i("info", "checked---------"
											+ radioButton.isChecked());
									if (radioButton.isChecked()) {
										temp=radioButton != null ? radioButton
												.getTag().toString() : "";
										break;
									}
								}
							}
						}
						if(temp.length()<1){
							isUnFilled=true;
						}
						pAns.append(temp);
						pAns.append("|TAG|");
						pReason.append("|TAG|");
						break;
					// CheckBox
					case 2:
						answerArea = (LinearLayout) this.findViewById(Integer
								.parseInt(key.toString()));
						StringBuilder chkValue = new StringBuilder("");
						CheckBox checkBox;
						for (int i = 0; i < answerArea.getChildCount(); i++) {
							view = answerArea.getChildAt(i);
							if (view instanceof LinearLayout) {
								templLayout = (LinearLayout) view;
								for (int y = 0; y < templLayout.getChildCount(); y++) {
									checkBox = (CheckBox) templLayout
											.getChildAt(y);
									if (checkBox == null) {
										isUnFilled = true;
									}
									if (checkBox.isChecked()) {
										chkValue.append(checkBox.getTag()
												.toString() + ",");
									}
								}
							}
						}
						if ("".equals(chkValue.toString())) {
							isUnFilled = true;
							pAns.append(chkValue.toString());
						} else {
							pAns.append(chkValue.toString().substring(0,
									chkValue.toString().length() - 1));
						}

						pAns.append("|TAG|");
						pReason.append("|TAG|");
						break;
					// EditBox
					case 3:
					case 4:
						EditText editText1 = (EditText) this
								.findViewById(Integer.parseInt(key.toString()));
						if (editText1.getText().toString().length()<1) {
							isUnFilled = true;
						}
						pAns.append(editText1.getText()
								.toString());
						pAns.append("|TAG|");
						pReason.append("|TAG|");
						break;
					case 5:
						answerArea = (LinearLayout) this.findViewById(Integer
								.parseInt(key.toString()));
						temp="";
						for (int i = 0; i < answerArea.getChildCount(); i++) {
							view = answerArea.getChildAt(i);
							if (view instanceof LinearLayout) {
								templLayout = (LinearLayout) view;
								for (int y = 0; y < templLayout.getChildCount(); y++) {
									radioButton = (RadioButton) templLayout
											.getChildAt(y);
									if (radioButton.isChecked()) {
										temp=radioButton != null ? radioButton
												.getTag().toString() : "";
										break;
									}
								}
							}
						}
						if(temp.length()<1){
							isUnFilled=true;
						}
						pAns.append(temp);
						pAns.append("|TAG|");
						reasText = (EditText) scrollView
								.findViewWithTag(answerArea.getId() + "_reason");
						if (null != reasText) {
							pReason.append(reasText.getText()
									.toString());
						}
						pReason.append("|TAG|");
						break;
					case 6:
						answerArea = (LinearLayout) this.findViewById(Integer
								.parseInt(key.toString()));
						temp="";
						for (int i = 0; i < answerArea.getChildCount(); i++) {
							view = answerArea.getChildAt(i);
							if (view instanceof LinearLayout) {
								templLayout = (LinearLayout) view;
								for (int y = 0; y < templLayout.getChildCount(); y++) {
									radioButton = (RadioButton) templLayout
											.getChildAt(y);
									if (radioButton.isChecked()) {
										temp=radioButton != null ? radioButton
												.getTag().toString() : "";
										break;
									}
								}
							}
						}
						if(temp.length()<1){
							isUnFilled=true;
						}
						pAns.append(temp);
						pAns.append("|");
						reasText = (EditText) scrollView
								.findViewWithTag(answerArea.getId() + "_reason");
						if (pAns.toString().indexOf("0") != -1) {
							pAns.append(reasText.getText()
									.toString());
						}

						pAns.append("|TAG|");
						pReason.append("|TAG|");
						break;
					}
				}
			}
			if (isUnFilled) {
				Dialog dialog = new AlertDialog.Builder(this)
						.setTitle("提交確認")
						.setMessage(
								getResources().getString(returnMsgSel("unfilled_tip")))
						.setPositiveButton("是",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										writeAnswerXML(pAns.toString(),
												pReason.toString());
									}
								})
						.setNegativeButton("否",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										dialog.dismiss();
									}
								}).create();
				dialog.show();
			} else {
				dialog = new AlertDialog.Builder(this)
						.setTitle("提交確認")
						.setMessage(
								getResources().getString(returnMsgSel("submitWarn")))
						.setPositiveButton("是",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										writeAnswerXML(pAns.toString(),
												pReason.toString());
									}
								})
						.setNegativeButton("否",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										dialog.dismiss();
									}
								}).create();
				dialog.show();
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("error", "答案區域獲取錯誤");
		}

	}

	/**
	 * 验证用户
	 * 
	 * @param path
	 * @return
	 * @throws Exception
	 */
	private void isUser(String path, View view) throws Exception {
		File file = new File(userPath);
		InputStream inputStream = new FileInputStream(file.getPath());
		SaxReadService readService = new SaxReadService();
		HashMap<String, User> usermap = readService.getUserInfo(inputStream, 4);
		EditText uname = (EditText) view.findViewById(R.id.uname);
		EditText pwd = (EditText) view.findViewById(R.id.pwd);
		if (null == uname.getText() || 0 == uname.getText().length()) {
			Toast.makeText(Qapaper.this, returnMsgSel("unameNull"), 5).show();
		}
		if (null == pwd.getText() || 0 == pwd.getText().length()) {
			Toast.makeText(Qapaper.this, returnMsgSel("pwdNull"), 5).show();
		}
		if (null == usermap.get(uname.getText().toString())) {
			Toast.makeText(Qapaper.this, returnMsgSel("valError"), 5).show();
			createLogin();
		} else {
			MD5 md5 = new MD5(pwd.getText().toString());
			String temp = md5.compute();
			User user = usermap.get(uname.getText().toString());
			if (temp.equalsIgnoreCase(user.getPwd())) {
				createTemplateSelect();
				this.user = user;
			} else {
				Toast.makeText(Qapaper.this, returnMsgSel("valError"), 5).show();
				createLogin();
			}
		}
	}

	/**
	 * 写答案XML格式文件
	 * 
	 * @param pAns
	 *            答案阵列
	 * @param pReason
	 *            不满意的原因
	 */
	public void writeAnswerXML(String pAns, String pReason) {
		try {
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String fileName = sdf.format(date);
			sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String pDate = sdf.format(date);

			StringBuffer data;
			File outputFile = null;
			if (null != configMap.get("mID")) {
				outputFile = new File(outPath + File.separatorChar
						+ configMap.get("mID") + fileName + ".xml");
			} else {
				outputFile = new File(outPath + File.separatorChar + fileName
						+ ".xml");
			}
			if (!outputFile.exists()) {
				data = new StringBuffer(
						"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<data>\n");
			} else {
				data = new StringBuffer("\n");
			}

			EditText editText = null;
			String pProject = "";
			StringBuffer pjID = new StringBuffer();
			View view = null;
			// 服務項目區域
			ScrollView scrollView = (ScrollView) this
					.findViewById(R.id.content_body);
			// 服務項目
			LinearLayout project_area = (LinearLayout) scrollView
					.findViewWithTag("peoject_area");

			for (int i = 0; i < project_area.getChildCount(); i++) {
				Log.i("info", "");
				view = project_area.getChildAt(i);

				if (view instanceof LinearLayout) {
					LinearLayout linearLayout = (LinearLayout) view;
					CheckBox checkBox = null;
					for (int y = 0; y < linearLayout.getChildCount(); y++) {
						checkBox = (CheckBox) linearLayout.getChildAt(y);
						if (checkBox.isChecked()) {
							pjID.append(checkBox.getTag()).append(",");
						}
					}
				}
				if (view instanceof EditText) {
					editText = (EditText) view;
					if (null != editText)
						pProject = editText.getText().toString();

				}
			}
			// 服務地點
			int unID = -1;
			String pUnit = "";
			Spinner spinner = null;
			LinearLayout unit_area = (LinearLayout) scrollView
					.findViewWithTag("unit_area");
			for (int i = 0; i < unit_area.getChildCount(); i++) {
				view = unit_area.getChildAt(i);
				if (view instanceof Spinner) {
					spinner = (Spinner) view;
					unID = spinner.getSelectedItemPosition();
				}
				if (view instanceof EditText) {
					editText = (EditText) view;
					pUnit = editText.getText().toString();
				}
			}
			// 校驗
			if (pjID.toString().length() < 1 && pProject.length() < 1) {
				Toast.makeText(Qapaper.this, returnMsgSel("valPro"), 5).show();
				return;
			}
			if (unID == -1 && pUnit.length() < 1) {
				Toast.makeText(Qapaper.this, returnMsgSel("valUnit"), 5).show();
				return;
			}
			// 获取pid值
			if (pidShared.getInt("pid", 0) != 0) {
				pID = pidShared.getInt("pid", 100001);
			}

			data.append("\t<paper>\n");
			data.append("\t\t<pID>" + isEncodeTxt(String.valueOf(pID)) + "</pID>\n");
			data.append("\t\t<tID>" + isEncodeTxt(questionFileName) + "</tID>\n");
			data.append("\t\t<pAns>" + isEncodeTxt(pAns.substring(0, pAns.length() - 5))
					+ "</pAns>\n");
			data.append("\t\t<pReason>"
					+ isEncodeTxt(pReason.substring(0, pReason.length() - 5))
					+ "</pReason>\n");
			data.append("\t\t<pjID>"
					+ isEncodeTxt(pjID.toString().substring(0, (pjID.length() - 1)))
					+ "</pjID>\n");
			data.append("\t\t<unID>"
					+ isEncodeTxt(String.valueOf((spinner.getSelectedItemPosition() + 1)))
					+ "</unID>\n");
			data.append("\t\t<pDate>" + isEncodeTxt(pDate) + "</pDate>\n");
			data.append("\t\t<pProject>" + isEncodeTxt(pProject)
					+ "</pProject>\n");
			data.append("\t\t<pUnit>" + isEncodeTxt(pUnit) + "</pUnit>\n");
			data.append("\t\t<uID>" + isEncodeTxt(this.user.getUid()) + "</uID>\n");
			data.append("\t</paper>\n");
			// data.append("<path>"+fileDirFile+"</path>");
			data.append("</data>");

			// 保存pid值供下次作答时使用，每作答一次即增量一次
			pID++;
			SharedPreferences.Editor editor = pidShared.edit();
			editor.putInt("pid", pID);

			// 写答案文件
			RandomAccessFile writer = null;
			String submitRes = "";
			try {
				writer = new RandomAccessFile(outputFile, "rw");
				if (outputFile.exists()) {
					String temp;
					while ((temp = writer.readLine()) != null) {
						if ("</data>".equalsIgnoreCase(temp)) {
							long tagPoint = writer.getFilePointer();
							writer.seek(tagPoint - 7);
							break;
						}
					}
				}
				writer.write(data.toString().getBytes());
				writer.close();
				submitRes = getResources().getString(returnMsgSel("submit_success"));
			} catch (Exception ex) {
				submitRes = getResources().getString(returnMsgSel("submit_fail"));
				ex.printStackTrace();
			} finally {
				Dialog dialog = new AlertDialog.Builder(this)
						.setTitle("提交結果")
						.setMessage(submitRes)
						.setPositiveButton("確定",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										ScrollView scrollView = (ScrollView) Qapaper.this
												.findViewById(R.id.content_body);
										scrollView.scrollTo(0, 0);
										dialog.dismiss();
										reset();
									}
								}).create();
				dialog.show();
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("error", "保存xml錯誤");
		}

	}

	/**
	 * 重置
	 */
	public void reset() {
		EditText editText = null;
		View view = null;
		// 服務項目區域
		ScrollView scrollView = (ScrollView) this
				.findViewById(R.id.content_body);
		// 服務項目
		LinearLayout project_area = (LinearLayout) scrollView
				.findViewWithTag("peoject_area");

		for (int i = 0; i < project_area.getChildCount(); i++) {
			Log.i("info", "");
			view = project_area.getChildAt(i);

			if (view instanceof LinearLayout) {
				LinearLayout linearLayout = (LinearLayout) view;
				CheckBox checkBox = null;
				for (int y = 0; y < linearLayout.getChildCount(); y++) {
					checkBox = (CheckBox) linearLayout.getChildAt(y);
					checkBox.setChecked(false);
				}
			}
			if (view instanceof EditText) {
				editText = (EditText) view;
				if (null != editText) {
					editText.setText("");
					editText.clearFocus();
				}
			}
		}
		// 服務地點
		Spinner spinner = null;
		LinearLayout unit_area = (LinearLayout) scrollView
				.findViewWithTag("unit_area");
		for (int i = 0; i < unit_area.getChildCount(); i++) {
			view = unit_area.getChildAt(i);
			if (view instanceof EditText) {
				editText = (EditText) view;
				editText.setText("");
				editText.clearFocus();
			}
		}
		LinearLayout answerArea = null;
		RadioButton radioButton = null;
		CheckBox cbk = null;
		for (Map<Integer, Integer> questionMap : Constants.questionViewsList) {
			Object[] keyArray = questionMap.keySet().toArray();
			try {
				for (Object key : keyArray) {
					view = this.findViewById(Integer.parseInt(key.toString()));
					if (view instanceof LinearLayout) {
						answerArea = (LinearLayout) this.findViewById(Integer
								.parseInt(key.toString()));
						for (int i = 0; i < answerArea.getChildCount(); i++) {
							Log.i("info", "");
							view = answerArea.getChildAt(i);

							if (view instanceof LinearLayout) {
								LinearLayout linearLayout = (LinearLayout) view;
								for (int y = 0; y < linearLayout
										.getChildCount(); y++) {
									view = linearLayout.getChildAt(y);
									if (view instanceof RadioButton) {
										radioButton = (RadioButton) view;
										if (null != radioButton)
											radioButton.setChecked(false);

									}
									if (view instanceof CheckBox) {
										cbk = (CheckBox) view;
										if (null != cbk)
											cbk.setChecked(false);

									}
									if (view instanceof EditText) {
										editText = (EditText) view;
										if (null != editText) {
											editText.setText("");
											editText.clearFocus();
											editText.setVisibility(View.GONE);
										}
									}
								}
							}
							if (view instanceof EditText) {
								editText = (EditText) view;
								if (null != editText) {
									editText.setText("");
									editText.clearFocus();
									editText.setVisibility(View.GONE);
								}

							}
						}
					}
					if (view instanceof EditText) {
						editText = (EditText) view;
						if (null != editText) {
							editText.setText("");
							editText.clearFocus();
						}
					}
				}
				scrollView.scrollTo(0, 0);
			} catch (Exception e) {
				e.printStackTrace();
				Log.e("error", "重置错误。");
			}

		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			dialog = new AlertDialog.Builder(this)
					.setTitle("提示")
					.setMessage(returnMsgSel("exitWarn"))
					.setPositiveButton("是",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									dialog.dismiss();
									System.exit(0);
								}
							})
					.setNegativeButton("否",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									dialog.dismiss();
								}
							}).create();
			dialog.show();
		}

		return false;
	}

	/**
	 * 检测配置文件，不存在则创建
	 */
	private void createConfigFile() {

		File outputFile = new File(inputPath + File.separatorChar
				+ "appConfig.xml");
		StringBuffer data = null;
		if (!outputFile.exists()) {
			if (!outputFile.exists()) {
				data = new StringBuffer(
						"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
			} else {
				data = new StringBuffer("\n");
			}
			data.append("\t<config>\n");
			data.append("\t\t <!--  標題字體大小-->\n");
			data.append("\t\t<title>20</title>\n");
			data.append("\t\t<!--子標題字體大小-->\n");
			data.append("\t\t<subTitle>20</subTitle>\n");
			data.append("\t\t<!--分類字體大小-->\n");
			data.append("\t\t<cname>26</cname>\n");
			data.append("\t\t<!--服務單位及選項字體大小-->\n");
			data.append("\t\t<unit>20</unit>\n");
			data.append("\t\t<!--服務項目及選項字體大小-->\n");
			data.append("\t\t<project>20</project>\n");
			data.append("\t\t<!--問卷選項字體大小-->\n");
			data.append("\t\t<item>26</item>\n");
			data.append("\t\t<!--是否用用戶自定義路徑，1：是，0：否-->\n");
			data.append("\t\t<isUserPath>0</isUserPath>\n");
			data.append("\t\t<!--自定義路徑-->\n");
			data.append("\t\t<userPath>/sdcard</userPath>\n");
			data.append("\t\t<!--mID-->\n");
			data.append("\t\t<mID>A</mID>\n");
			data.append("\t\t<!--是否加密-->\n");
			data.append("\t\t<isEncode>0</isEncode>\n");
			data.append("\t\t<!--是否简体-->\n");
			data.append("\t\t<isZhcn>0</isZhcn>\n");
			data.append("\t</config>\n");
			RandomAccessFile writer = null;
			try {
				writer = new RandomAccessFile(outputFile, "rw");
				if (outputFile.exists()) {
					String temp;
					while ((temp = writer.readLine()) != null) {
						if ("</data>".equalsIgnoreCase(temp)) {
							long tagPoint = writer.getFilePointer();
							writer.seek(tagPoint - 7);
							break;
						}
					}
				}
				writer.write(data.toString().getBytes());
				writer.close();
			} catch (Exception e) {
				e.printStackTrace();
				Log.e("erroe", "生成配置文件錯誤");
			}
		}

	}

	/**
	 * 讀取配置文件具體項
	 * 
	 * @param key
	 * @return
	 */
	private HashMap<String, String> getConfigMap() {
		try {
			InputStream inputStream = new FileInputStream(inputPath
					+ File.separatorChar + "appConfig.xml");
			ConfigReadService config = new ConfigReadService();
			HashMap<String, String> configMap = config.getConfig(inputStream);
			if (null != configMap.get("title")) {
				titleSize = Integer.parseInt(configMap.get("title"));
			}
			if (null != configMap.get("subTitle")) {
				subTitleSize = Integer.parseInt(configMap.get("subTitle"));
			}
			if (null != configMap.get("cname")) {
				cnameSize = Integer.parseInt(configMap.get("cname"));
			}
			return configMap;

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * 创建模板选择框
	 */
	private void createTemplateSelect() {
		try {
			List<String> quss=qusList();
			HashMap<String, TemplateInfo> templateInfos=getTemplateMap();
			LayoutInflater factory = LayoutInflater.from(Qapaper.this);
			final View view = factory.inflate(R.layout.template, null);
			ScrollView scrollView = (ScrollView) view.findViewById(R.id.scview);
			scrollView.setBackgroundColor(Color.WHITE);
			LinearLayout tempLayout = null;
			TextView title = null;
			TextView subTitle = null;
			LinearLayout lineItem = new LinearLayout(Qapaper.this);
			lineItem.setOrientation(LinearLayout.VERTICAL);
			if (quss.size() == 1) {
				global_title = templateInfos.get(quss.get(0)).getTitle();
				global_subtitle = templateInfos.get(quss.get(0)).getSubtitle();
				tempSpinnerIndex="0";
				tid= templateInfos.get(quss.get(0)).getTid();
				// 创建界面
				LinearLayout linearLayout = createPaper(templateInfos.get(quss.get(0))
						.getFeedback());
				ScrollView scrollViewBody = (ScrollView) findViewById(R.id.content_body);
				scrollViewBody.addView(linearLayout);
			} else {
				int index=0;
				for (int i = 0,len=quss.size(); i < len; i++) {
						templateMap
								.put(String.valueOf(index), templateInfos.get(quss.get(i)));
						tempLayout = new LinearLayout(view.getContext());
						tempLayout.setOrientation(LinearLayout.VERTICAL);
						title = new TextView(view.getContext());
						title.setTextSize(22);
						title.setVisibility(View.GONE);
						subTitle = new TextView(view.getContext());
						subTitle.setTextSize(20);
						title.setText(templateInfos.get(quss.get(i)).getTitle());
						subTitle.setText(templateInfos.get(quss.get(i)).getSubtitle());
						subTitle.setVisibility(View.GONE);
						TextView tempIndex = new TextView(this);
						tempIndex.setText(String.valueOf(index));
						tempIndex.setVisibility(View.GONE);
						TextView tnameTextView = new TextView(this);
						tnameTextView.setTextSize(26);
						tnameTextView.setTextColor(Color.BLACK);
						tnameTextView.setText(templateInfos.get(quss.get(i)).getName());
						TextView tempTid = new TextView(this);
						tempTid.setText(templateInfos.get(quss.get(i)).getTid());
						tempTid.setVisibility(View.GONE);
						tempLayout.addView(title, new LayoutParams(
								LayoutParams.FILL_PARENT,
								LayoutParams.WRAP_CONTENT));
						tempLayout.addView(subTitle, new LayoutParams(
								LayoutParams.FILL_PARENT,
								LayoutParams.WRAP_CONTENT));
						tempLayout.addView(tempIndex, new LayoutParams(
								LayoutParams.FILL_PARENT,
								LayoutParams.WRAP_CONTENT));
						tempLayout.addView(tnameTextView, new LayoutParams(
								LayoutParams.FILL_PARENT,
								LayoutParams.WRAP_CONTENT));
						tempLayout.addView(tempTid, new LayoutParams(
								LayoutParams.FILL_PARENT,
								LayoutParams.WRAP_CONTENT));
						index++;
						tempLayout.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								// v.setBackgroundColor(Color.parseColor("#cbf77e"));
								LinearLayout item = (LinearLayout) v;
								TextView text = (TextView) item.getChildAt(0);
								global_title = text.getText().toString();
								text = (TextView) item.getChildAt(1);
								global_subtitle = text.getText().toString();
								text = (TextView) item.getChildAt(2);
								tempSpinnerIndex = text.getText().toString();
								text = (TextView) item.getChildAt(4);
								tid = text.getText().toString();
								templateDialog.dismiss();
								// 创建界面
								LinearLayout linearLayout = createPaper(templateMap
										.get(tempSpinnerIndex).getFeedback());
								ScrollView scrollView = (ScrollView) findViewById(R.id.content_body);
								scrollView.addView(linearLayout);

							}
						});
						lineItem.addView(tempLayout, new LayoutParams(
								LayoutParams.FILL_PARENT, 30));
						if (i % 2 == 0) {
							tempLayout.setBackgroundColor(Color
									.parseColor("#D9D9D9"));
						}
				}
				scrollView.addView(lineItem);
				templateDialog = new AlertDialog.Builder(Qapaper.this)
						.setView(view)
						.setTitle("模板選擇")
						.setNegativeButton("退出",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										Dialog exitDialog = new AlertDialog.Builder(
												Qapaper.this)
												.setTitle("提示")
												.setMessage(returnMsgSel("exitWarn"))
												.setPositiveButton(
														"是",
														new DialogInterface.OnClickListener() {
															public void onClick(
																	DialogInterface dialog,
																	int whichButton) {
																dialog.dismiss();
																System.exit(0);
															}
														})
												.setNegativeButton(
														"否",
														new DialogInterface.OnClickListener() {
															public void onClick(
																	DialogInterface dialog,
																	int whichButton) {
																dialog.dismiss();
															}
														}).create();
										exitDialog.show();

									}
								}).create();
				templateDialog.show();
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("error", "读取模板列表错误");
		}
	}

	private void createQuestionArea(LinearLayout linearLayout, File file,
			String isShowInput) {
		try {
			createViewItem createViewItem = new createViewItem(Qapaper.this,
					isShowInput);
			SaxReadService readService = new SaxReadService();
			InputStream inputStream;
			File[] files = file.listFiles();
			String tempQusPath = "";
			String fileName = "";
			for (int i = 0; i < files.length; i++) {
				fileName = files[i].toString();
				fileName = fileName.substring(fileName.lastIndexOf("/") + 1,
						fileName.lastIndexOf("."));
				if (tid.equalsIgnoreCase(fileName)) {
					tempQusPath = files[i].getPath();
					break;
				}
			}
			if (tempQusPath == "") {
				info = returnMsgSel("errorTid");
				Toast.makeText(Qapaper.this, info, 5).show();
			}

			File typeFile = new File(qusTypePath);
			// 分類顯示，否則原樣輸出
			if (typeFile.exists()) {
				inputStream = new FileInputStream(typeFile);
				// 分類集合
				List<CategoriesInfo> categoriesInfos = readService
						.getCategoriesInfo(inputStream, 3);
				inputStream = new FileInputStream(tempQusPath);
				questionFileName = fileName;
				// 問題結合
				List<Question> questions = readService.getQuestions(
						inputStream, 1);
				questionArraySort qSort = new questionArraySort(getConfigMap(),
						isShowInput);
				HashMap<String, Object> listMap = qSort.sortQuestion(
						Qapaper.this, categoriesInfos, questions);
				TextView textView = null;
				for (int i = 0; i < categoriesInfos.size(); i++) {
					@SuppressWarnings("unchecked")
					ArrayList<LinearLayout> listItems = (ArrayList<LinearLayout>) listMap
							.get(String.valueOf(i + 1));
					if (listItems.size() > 0) {
						textView = new TextView(Qapaper.this);
						textView.setLayoutParams(new LayoutParams(240,
								LayoutParams.WRAP_CONTENT));
						textView.setBackgroundColor(Color.parseColor("#D9D9D9"));
						textView.setTextColor(Color.parseColor("#1f1313"));
						textView.setTextSize(cnameSize);
						textView.setText(listMap.get(
								String.valueOf(i + 1) + "_name").toString());
						linearLayout.addView(textView);
						for (LinearLayout lay : listItems) {
							linearLayout.addView(lay);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private List<String> qusList() {
		File file = new File(questionPath);
		List<String> qusList=null;
		String tempName="";
		// 做问卷选择
		File[] files = file.listFiles();
		if(files.length>0){
			qusList=new ArrayList<String>();
			for (int i = 0, len = files.length; i < len; i++) {
				tempName=files[i].getName();
				tempName=tempName.substring(0,tempName.indexOf("."));
				qusList.add(tempName);
			}
		}
		return qusList;
	}
	
	/**
	 * 返回模板map
	 * @return
	 */
	private HashMap<String, TemplateInfo> getTemplateMap(){
		HashMap<String, TemplateInfo> tempHashMap=null;
		try {
			SaxReadService readService = new SaxReadService();
			FileInputStream inputStream = new FileInputStream(templateFilePath);
			List<TemplateInfo> templateInfos = readService.getTemplate(
					inputStream, 2);
			tempHashMap=new HashMap<String, TemplateInfo>();
			for(TemplateInfo template:templateInfos){
				tempHashMap.put(template.getTid(), template);
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("error","封裝termplateMap錯誤");
		}
		return tempHashMap;
	}
	
	private String isEncodeTxt(String txt){
		if (configMap.get("isEncode").equals("1")) {
			return URLEncoder.encode(base64Util.encode(txt.getBytes()));
		}else{
			return URLEncoder.encode(txt);
		}
	}
	private void fillMsgMap(){
		msgMap.put("app_name", R.string.app_name);
		msgMap.put("app_name_sim", R.string.app_name_sim);
		
		msgMap.put("errorTid", R.string.errorTid);
		msgMap.put("errorTid_sim", R.string.errorTid_sim);
		
		msgMap.put("exitWarn", R.string.exitWarn);
		msgMap.put("exitWarn_sim", R.string.exitWarn_sim);
		
		msgMap.put("noAppPath", R.string.noAppPath);
		msgMap.put("noAppPath_sim", R.string.noAppPath_sim);
		
		msgMap.put("noTemplate", R.string.noTemplate);
		msgMap.put("noTemplate_sim", R.string.noTemplate_sim);
		
		msgMap.put("noType", R.string.noType);
		msgMap.put("noType_sim", R.string.noType_sim);
		
		msgMap.put("nofile", R.string.nofile);
		msgMap.put("nofile_sim", R.string.nofile_sim);
		
		msgMap.put("pwdNull", R.string.pwdNull);
		msgMap.put("pwdNull_sim", R.string.pwdNull_sim);
		
		msgMap.put("submitWarn", R.string.submitWarn);
		msgMap.put("submitWarn_sim", R.string.submitWarn_sim);
		
		msgMap.put("unameNull", R.string.unameNull);
		msgMap.put("unameNull_sim", R.string.unameNull_sim);
		
		msgMap.put("unfilled_tip", R.string.unfilled_tip);
		msgMap.put("unfilled_tip_sim", R.string.unfilled_tip_sim);
		
		msgMap.put("valError", R.string.valError);
		msgMap.put("valError_sim", R.string.valError_sim);
		
		msgMap.put("valPro", R.string.valPro);
		msgMap.put("valPro_sim", R.string.valPro_sim);
		
		msgMap.put("valUnit", R.string.valUnit);
		msgMap.put("valUnit_sim", R.string.valUnit_sim);
		
		msgMap.put("withOutSD", R.string.withOutSD);
		msgMap.put("withOutSD_sim", R.string.withOutSD_sim);
		
		msgMap.put("errorTid", R.string.errorTid);
		msgMap.put("errorTid_sim", R.string.errorTid_sim);
		
		msgMap.put("submit_success", R.string.submit_success);
		msgMap.put("submit_success_sim", R.string.submit_success_sim);
		
		msgMap.put("submit_fail", R.string.submit_fail);
		msgMap.put("submit_fail_sim", R.string.submit_fail_sim);
		
		
		
	}
	private  int returnMsgSel(String key){
		if (configMap.get("isZhcn").equalsIgnoreCase("0")) {
			return msgMap.get(key);
		}else{
			return msgMap.get(key+"_sim");
		}
	}
}